package com.xj.lucene;

import org.apache.lucene.index.AtomicReaderContext;
import org.apache.lucene.queries.CustomScoreProvider;
import org.apache.lucene.queries.CustomScoreQuery;
import org.apache.lucene.search.FieldCache;
import org.apache.lucene.search.FieldCache.Longs;
import org.apache.lucene.search.Query;

import java.io.IOException;

public class RecencyBoostingQuery extends CustomScoreQuery {
	private long size;
	private float boost = 1.0f;

	public RecencyBoostingQuery(Query subQuery, long size, float boost) {
		super(subQuery);
		this.size = size;
		this.boost=boost;
	}

	private class RecencyBooster extends CustomScoreProvider {
		Longs sizes = null;

		@Override
		public float customScore(int doc, float subQueryScore, float valSrcScore) throws IOException {
			long s = sizes.get(doc);
			float _boost =1.0f;
			if (s < size) {
				_boost = boost;
			}
			// return super.customScore(doc, subQueryScore, valSrcScore);
			return subQueryScore * _boost;
		}

		public RecencyBooster(AtomicReaderContext context) {
			super(context);
			try {
				sizes = FieldCache.DEFAULT.getLongs(context.reader(), "size", true);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	protected CustomScoreProvider getCustomScoreProvider(AtomicReaderContext context) throws IOException {
		return new RecencyBooster(context);
	}

}
